//
//  FCRelationTypeManagerViewController.m
//  customerRelation
//
//  Created by 陈文斌 on 2019/5/29.
//

#import "FCRelationTypeManagerViewController.h"
#import "FCBtnTypeRuleView.h"
#import "CustomerRelationHeader.h"
#import "TableTextFeildViewCell.h"
#import "FCAlertViewController.h"
#import "FCRelationTypeListModel.h"
#import "FCCustomerRelationRequest.h"
#import "UIViewController+runtimeCheck.h"
@interface FCRelationTypeManagerViewController ()
<
btnTypeRuleDelegate,
UITableViewDelegate,
UITableViewDataSource,
UITextFieldDelegate
>

@property (nonatomic,strong) NSMutableArray<FCRelationTypeModel *> *showArr;
@property (nonatomic,strong) FCBtnTypeRuleView *btnView;
@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic, strong) UITextField *oldTextField;
@property (nonatomic, strong) NSMutableArray<FCRelationTypeModel *> *newShowArr;

@end

@implementation FCRelationTypeManagerViewController
- (NSMutableArray *)showArr{
    if (!_showArr) {
        _showArr = [NSMutableArray array];
        
    }
    return _showArr;
}
- (NSMutableArray<FCRelationTypeModel *> *)newShowArr{
    if (!_newShowArr) {
        _newShowArr = [NSMutableArray array];
    }
    return _newShowArr;
}

-(void)setRuleView{
    self.tableView.frame=CGRectMake(0, 0, WJCScreenW, WJCScreenH-FCNavBarHeight-70);
    _btnView=[[FCBtnTypeRuleView alloc] initWithFrame:CGRectMake(16, self.tableView.y+self.tableView.height+12, WJCScreenW-32, 42)];
    _btnView.backgroundColor=[UIColor whiteColor];
    _btnView.delegate=self;
    NSArray *arr=@[
                   @{@"titleTxt":customerRelationLocaChanged(@"添加关系类型",@"添加关系类型"),@"titleColor":FCWhiteColor,@"backColor":FCBlueBackColor,@"btnType":@(btnNomal)},
                   ];
    
    NSMutableArray *btnArr=[NSMutableArray new];
    for (NSDictionary *dic in arr) {
        btnTypeModel *btnType=[[btnTypeModel alloc] init];
        [btnType setValuesForKeysWithDictionary:dic];
        [btnArr addObject:btnType];
    }
    _btnView.ruleType=ruleAverage;
    _btnView.btnArr=btnArr;
    [self.view addSubview:_btnView];
    [self.tableView setEditing:YES animated:YES];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.and.left.and.right.mas_equalTo(0);
        make.bottom.mas_equalTo(-60);
    }];
    [self.btnView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(16);
        make.right.mas_equalTo(-16);
        make.bottom.mas_equalTo(-10);
        make.height.mas_equalTo(42);
    }];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor=FCWhiteColor;
    self.title=customerRelationLocaChanged(@"关系类型管理",@"关系类型管理");
    self.tableView=[[UITableView alloc]initWithFrame:CGRectMake(0, 0, WJCScreenW, WJCScreenH-64) style:UITableViewStylePlain];
    self.tableView.estimatedSectionHeaderHeight = 0;
    self.tableView.estimatedSectionFooterHeight = 0;
    self.tableView.backgroundColor=FCBackColor;
    self.tableView.tableFooterView=[UIView new];
    self.tableView.allowsSelectionDuringEditing=YES;
    self.tableView.dataSource=self;
    self.tableView.delegate=self;
    [self.view addSubview:self.tableView];
    [self getCacheData];
    
    [self setRuleView];
}

#pragma mark - Table view data source

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return _showArr.count;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.001f;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if (section==1) {
        return 5;
    }
    return 0.001f;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 48;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    TableTextFeildViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"TxtChoicecell"];
    if (!cell) {
        cell=[[TableTextFeildViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"TxtChoicecell"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.titleTextField.y=(48-cell.titleTextField.height)*0.5;
    }

    cell.titleTextField.text=_showArr[indexPath.row].name;
    WJCWeakSelf
    cell.textFieldShouldReturnBlock = ^(NSString * _Nonnull text) {
        XMGLog(@"%@    %@",cell.titleTextField.text, text);
        if (text.length < 1) {
            [SVProgressHUD showInfoWithStatus:@"管理类型名称不能为空"];
            return ;
        }
        NSDictionary *args = @{
                               @"id": weakSelf.showArr[indexPath.row].Id,
                               @"name": text
                               };
        [FCCustomerRelationRequest addOrUpdateRelationTypeWithArgs:args success:^(id resultObj) {
            XMGLog(@"编辑成功 %@",resultObj);
            weakSelf.showArr[indexPath.row].name = text;
            [SVProgressHUD dismiss];
        } failure:^(NSError *error) {
            [self.tableView reloadData];
        }];
    };
    
    return cell;
}
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleDelete;
}
- (NSArray *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath{
    //设置删除按钮
    WJCWeakSelf
    UITableViewRowAction *deleteRowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal title:customerRelationLocaChanged(@"global_general_delete", @"删除") handler:^(UITableViewRowAction *action,NSIndexPath *indexPath) {
        FCRelationTypeModel *type = weakSelf.showArr[indexPath.row];
        [FCAlertViewController alertCommonWithTitle:[NSString stringWithFormat:@"确定删除“%@”关系类型？",type.name] andSubTitle:nil andController:weakSelf andCommitAction:^(FCAlertAction *action) {
            dispatch_async(dispatch_get_main_queue(), ^{
                FCRelationTypeModel *relationType = weakSelf.showArr[indexPath.row];
                
                NSDictionary *args = @{
                                       @"ids": @[relationType.Id]
                                       };
                [FCCustomerRelationRequest deleteRelationTypeWithArgs:args vc:weakSelf success:^(id resultObj) {
                    [SVProgressHUD dismiss];
                    [weakSelf.showArr removeObjectAtIndex:indexPath.row];
                    [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationRight];
                    [saveSandBox DELETEDataWithType:nil andOther:nil andClass:[FCRelationTypeModel class]];
                } failure:^(NSError *error) {
                    [tableView reloadData];
                }];
            });
        }];
    }];
    deleteRowAction.backgroundColor=[UIColor redColor];
    
    return  @[deleteRowAction];
    
}

/**
 修改移动三条杠的图片
 
 */
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    
    for (UIView *view in cell.subviews) {
        if ([[[view class] description]isEqualToString:@"UITableViewCellReorderControl"]) {
            for (UIView *v in view.subviews) {
                if ([v isKindOfClass:[UIImageView class]]) {
                    [v removeFromSuperview];
                }
            }
            UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(5,13, 22,22)];
            imageView.image = customerRelationImageName(@"ic_manage_move");
            [view addSubview:imageView];
        }
    }
}

-(void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath{
        [_showArr exchangeObjectAtIndex:sourceIndexPath.row withObjectAtIndex:destinationIndexPath.row];
    
    
        NSMutableArray *arr=[NSMutableArray new];
        for (int i=0; i<self.showArr.count; i++) {
            [arr addObject:self.showArr[i].Id];
        }
        
        NSDictionary *args = @{
                               @"ids": arr
                               };
        [FCCustomerRelationRequest sortRelationTypeWithArgs:args success:^(id resultObj) {
            [SVProgressHUD dismiss];
        } failure:^(NSError *error) {
            
        }];
        
        [tableView reloadData];
}

-(void)btnTypeRuleClickWithBtn:(UIButton *)sender andView:(FCBtnTypeRuleView *)view{
    FCAlertViewController *controller=[[FCAlertViewController alloc] initWithTitle:customerRelationLocaChanged(@"添加关系类型",@"添加关系类型") andSubTitle:nil andAlertType:FCAlertTxt];
    [controller addTextFieldWithConfigurationHandler:^(UITextField *textField) {
        textField.placeholder=customerRelationLocaChanged(@"请输入关系类型",@"请输入关系类型");
        [textField setValue:font15 forKeyPath:@"_placeholderLabel.font"];
        [textField setBackgroundColor:FCBackColor];
        textField.borderStyle = UITextBorderStyleNone;
        textField.textAlignment = NSTextAlignmentCenter;
        [textField becomeFirstResponder];
        textField.delegate = self;
    }];
    FCAlertAction *commitAction=[FCAlertAction actionWithTitle:customerRelationLocaChanged(@"global_general_confirm",@"确定") style:FCAlertActionDefault handler:^(FCAlertAction *action) {
        UITextField *txt=controller.txtFieldArr[0];
        if (txt.text.length>0) {
            if (txt.text.length>5) {
                [SVProgressHUD showErrorWithStatus:customerRelationLocaChanged(@"关系类型名称长度不能大于5",@"关系类型名称长度不能大于5")];
                return;
            }
            NSDictionary *args = @{
                                   @"name": txt.text
                                   };
            [FCCustomerRelationRequest addOrUpdateRelationTypeWithArgs:args success:^(id resultObj) {
                XMGLog(@"添加成功 ： %@",resultObj);
                NSDictionary *result = resultObj[@"data"][@"crmSupplyRelationTypeAou"];
                FCRelationTypeModel *relationType = [FCRelationTypeModel mj_objectWithKeyValues:result];
                [self.showArr addObject:relationType];
                [self.tableView reloadData];
            } failure:^(NSError *error) {
                [SVProgressHUD dismiss];
            }];
        }
        else {
            [SVProgressHUD showErrorWithStatus:customerRelationLocaChanged(@"请输入关系类型名称",@"请输入关系类型名称")];
        }
    }];
    FCAlertAction *cancelAction=[FCAlertAction actionWithTitle:customerRelationLocaChanged(@"global_general_cancel",@"取消") style:FCAlertActionCancel handler:^(FCAlertAction *action) {
        
    }];
    [controller addAction:cancelAction];
    [controller addAction:commitAction];
    
    [self presentViewController:controller animated:YES completion:nil];
}

#pragma mark - textField delegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    if (range.length == 1 && string.length == 0) {
        return YES;
    } else if (textField.text.length >= 5) {
        textField.text = [textField.text substringToIndex:5];
        return NO;
    }
    return YES;
}

// 刷新数据
- (void)updateData{
    // 清除旧数据
    [self.newShowArr removeAllObjects];
    // 加载新数据
    [self getRelationTypesData];
}

// 获取缓存数据
- (void)getCacheData{
    //获取缓存数据
    NSArray *cache = [FCFuChengCacheTool getHttpCacheWithUrlString:FCCrmSupplyRelationTypesDataKey parameters:nil];
    NSMutableArray *cacheResult = [FCRelationTypeModel mj_objectArrayWithKeyValuesArray:cache];
    if (cacheResult.count) {
        self.newShowArr = cacheResult;
        self.showArr = [[NSMutableArray alloc] initWithArray:self.newShowArr];
        [self.tableView reloadData];
    }
    // 刷新新数据
    [self updateData];
    // 开启数据变化监听
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateData) name:CrmSupplyRelationChanged object:nil];
}

// 获取关系类型
- (void)getRelationTypesData{
        NSNumber *take = @(5);
        NSDictionary *args = @{@"enable": @(YES),
                               @"take": take,
                               @"skip": @(self.newShowArr.count)
                               };
        WJCWeakSelf
        [FCCustomerRelationRequest getCrmSupplyRelationTypeWithArgs:args success:^(id resultObj) {
            FCRelationTypeListModel *relationTypesModel = [FCRelationTypeListModel mj_objectWithKeyValues:resultObj[@"data"][@"crmSupplyRelationTypes"]];
            
            [weakSelf.newShowArr addObjectsFromArray:relationTypesModel.items];
            
            if (weakSelf.newShowArr.count >= relationTypesModel.pageInfo.total) {
                XMGLog(@"relationType 全部请求完成");
                weakSelf.showArr = [[NSMutableArray alloc] initWithArray:weakSelf.newShowArr];
                [weakSelf.tableView reloadData];
                //缓存
                NSArray *cache = [FCRelationTypeModel mj_keyValuesArrayWithObjectArray:self.showArr];
                [FCFuChengCacheTool saveHttpCache:cache urlString:FCCrmSupplyRelationTypesDataKey parameters:nil];
            } else {
                XMGLog(@"relationType 继续请求");
                [weakSelf getRelationTypesData];
            }
        } failure:^(NSError *error) {
            [SVProgressHUD dismiss];
            XMGLog(@"%@", error);
        }];
}

@end
